import React, { useState, useEffect,useRef } from "react";
import { 
  Text, 
  View, 
  StyleSheet, 
  Button, 
  TouchableOpacity, 
  Image,
} from "react-native";
import { Camera, CameraView } from "expo-camera";
// import ScannerOverlays from '../component/scanner_overlays';  // 引入 ScannerOverlays 组件
import ScannerAnimation from '../component/scanner_animation'; // 引入扫描动画

export default function App() {
  const [hasPermission, setHasPermission] = useState<boolean | null>(null);
  const [scanned, setScanned] = useState(false);
  const [isTorchEnabled, setIsTorchEnabled] = useState(false); // 控制手电筒开关
   const [zoom, setZoom] = useState(0); // 控制摄像头缩放
  const zoomRef = useRef(0); // 存储当前 zoom 值，避免重复设置

    // 同步zoom状态到ref
    useEffect(() => {
      zoomRef.current = zoom;
    }, [zoom]);


  useEffect(() => {
    const getCameraPermissions = async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === "granted" ? true : false);
    };

    getCameraPermissions();
  }, []);

  const handleBarcodeScanned = ({
    type,
    data,
    bounds,
  }: {
    type: string;
    data: string;
    bounds: {
      origin: { x: number; y: number };
      size: { width: number; height: number };
    };
  }) => {
    const MIN_WIDTH = 60; // 最小有效宽度
    const ZOOM_STEP = 0.3; // 每次缩放步长

    console.log("扫描到二维码:", {
      type,
      data,
      width: bounds.size.width,
      height: bounds.size.height,
      currentZoom: zoomRef.current,
    });

    // 当二维码宽度小于阈值时自动放大
    if (bounds.size.width < MIN_WIDTH) {
      const newZoom = Math.min(zoomRef.current + ZOOM_STEP, 1);
      console.log(`二维码过小（${bounds.size.width} < ${MIN_WIDTH}），调整zoom至: ${newZoom}`);
      setZoom(newZoom);
    } else {
      console.log("二维码尺寸有效，处理数据...");
      setScanned(true);
      alert(`类型: ${type}\n数据: ${data}`);
    }
  };

  if (hasPermission === null) return <Text>请求相机权限</Text>;
  if (hasPermission === false) return <Text>没有相机权限</Text>;


  return (
    <View style={styles.container}>
      {/* 相机视图区域 */}
      <CameraView
        enableTorch={isTorchEnabled} // 根据状态控制手电筒
        onBarcodeScanned={scanned ? undefined : handleBarcodeScanned}
        barcodeScannerSettings={{
          barcodeTypes: ["qr", "pdf417"],
        }}
        style={StyleSheet.absoluteFillObject} // 让相机全屏
        zoom={zoom} // 绑定zoom状态
      />

      {/* <ScannerOverlays />  渲染蒙层和扫描区域 */}

      {/* 扫描动画区域 */}
      <ScannerAnimation />
      {/* 手电筒控制按钮 */}
      <TouchableOpacity
        style={styles.torchButton}
        onPress={() => setIsTorchEnabled(prevState => !prevState)} // 切换手电筒状态
      >
        {/* 手电筒图标 */}
        <Image
          source={isTorchEnabled ? require('../assets/scanner/手电筒开.png') : require('../assets/scanner/手电筒关.png')} // 根据手电筒状态显示不同的图标
          style={styles.torchIcon}
        />

      </TouchableOpacity>
      {scanned && (
        <Button
          title="点击重新扫描"
          onPress={() => {
            setScanned(false);
            setZoom(0); // 重置缩放
            console.log("重置摄像头缩放");
          }}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  overlay: {
    position: "absolute",
    width: "100%",
    height: "100%",
    justifyContent: "center",
  },
  torchButton: {
    position: 'absolute',
    top: '50%', // 中心位置
    left: '50%',
    transform: [{ translateX: -25 }, { translateY: -25 }],
  },
  torchIcon: {
    width: 50,
    height: 50,
  },
});

